
package cn.jsc.order.service.impl;

import cn.jsc.basic.service.impl.BaseServiceImpl;
import cn.jsc.basic.util.CodeGenerateUtils;
import cn.jsc.basic.util.DistanceUtil;
import cn.jsc.basic.util.LoginContextUtil;
import cn.jsc.basic.util.PageList;
import cn.jsc.order.domain.AdoptOrder;
import cn.jsc.order.domain.OrderAddress;
import cn.jsc.order.domain.ProductOrder;
import cn.jsc.order.domain.ProductOrderDetail;
import cn.jsc.order.mapper.OrderAddressMapper;
import cn.jsc.order.mapper.ProductOrderDetailMapper;
import cn.jsc.order.mapper.ProductOrderMapper;
import cn.jsc.order.query.AdoptOrderQuery;
import cn.jsc.order.query.ProductOrderQuery;
import cn.jsc.order.service.IProductOrderService;
import cn.jsc.org.domain.Employee;
import cn.jsc.org.domain.Shop;
import cn.jsc.org.mapper.EmployeeMapper;
import cn.jsc.org.mapper.ShopMapper;
import cn.jsc.pay.constants.PayConstants;
import cn.jsc.pay.domain.PayBill;
import cn.jsc.pay.mapper.PayBillMapper;
import cn.jsc.pay.service.IPayBillService;
import cn.jsc.product.domain.Product;
import cn.jsc.product.mapper.ProductMapper;
import cn.jsc.quartz.constants.JobConstants;
import cn.jsc.quartz.dto.QuartzJobInfo;
import cn.jsc.quartz.service.IQuartzService;
import cn.jsc.user.domain.LoginInfo;
import cn.jsc.user.domain.User;
import cn.jsc.user.domain.UserAddress;
import cn.jsc.user.mapper.UserAddressMapper;
import cn.jsc.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IQuartzService quartzService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public String submit(Map<String, Object> params, LoginInfo loginInfo) {
        Long addressId = Long.parseLong(params.get("address_id").toString());
        Long productId = Long.parseLong(params.get("product_id").toString());
        Long pay_method = Long.parseLong(params.get("pay_method").toString());

        Product product = productMapper.loadById(productId);
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        //1创建订单
        //1.1 创建订单

        ProductOrder productOrder = getProductOrder(params,userAddress,product,user);
        productOrderMapper.save(productOrder);
        //1.2 保存关联表 orderAdress productOrderDetail

        System.out.println(productOrder.getId());
        OrderAddress orderAddress = userAddress2orderAddress(userAddress);
        orderAddress.setOrder_id(productOrder.getId());
        orderAddress.setOrderSn(productOrder.getOrderSn());
        orderAddressMapper.save(orderAddress);

        ProductOrderDetail productOrderDetail = product2productOrderDetail(product);
        productOrderDetail.setOrder_id(productOrder.getId());
        productOrderDetailMapper.save(productOrderDetail);

        // 2 创建支付单
        PayBill payBill = order2PayBill(pay_method, productOrder, user);
        payBillMapper.save(payBill);

        // 3 订单倒计时取消处理
        QuartzJobInfo info = new QuartzJobInfo();
        info.setType(JobConstants.OVER_TIME_NO_PAY_PRODUCT);
        String jobName = JobConstants.OVER_TIME_NO_PAY_PRODUCT+ payBill.getUnionPaySn();
        Map<String, Object> infoParams = new HashMap<>();
        infoParams.put("orderId",productOrder.getId());
        Date fireDate = productOrder.getLastPayTime();
        info.setJobName(jobName);
        info.setParams(infoParams);
        info.setFireDate(fireDate);
        quartzService.add(info);
        System.out.println("订单倒计时取消任务【" + info.getJobName() + "】创建成功...");
        // 4 跳转到支付页面,通过调用支付接口，要把这个数据返回前台，前台处理后跳转支付宝支付页面
        String payData = payBillService.payRequest(payBill);
        return payData;
    }

    @Override
    public void cancelOrder(Long orderId) {
        ProductOrder productOrder = productOrderMapper.loadById(orderId);
        if(productOrder.getState()!=-1){
            productOrder.setState(-1);
            productOrderMapper.update(productOrder);
        }

        String paySn = productOrder.getPaySn();
        PayBill payBill = payBillMapper.loadByUnionPaySn(paySn);
        if (payBill.getState()!=-1){
            payBill.setState(-1);
            payBillMapper.update(payBill);
        }

    }

    /**
     * 管理员查询领养订单
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<ProductOrder> admin(ProductOrderQuery query, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
        query.setShop_id(employee.getShop_id());
        return super.queryData(query);
    }

    /**
     * 用户查询领养订单
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<ProductOrder> user(ProductOrderQuery query, HttpServletRequest request) {
        LoginInfo loginInfo = LoginContextUtil.getLoginInfo(request);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        query.setUser_id(user.getId());
        return super.queryData(query);
    }

    private PayBill order2PayBill(Long pay_method, ProductOrder productOrder,User user) {
        PayBill payBill = new PayBill();
        payBill.setDigest(productOrder.getDigest());
        payBill.setMoney(productOrder.getPrice());
        payBill.setUnionPaySn(productOrder.getPaySn());
        payBill.setState(0);
        payBill.setLastPayTime(productOrder.getLastPayTime());
        payBill.setPayChannel(pay_method);
        payBill.setBusinessType(PayConstants.BUSINESS_TYPE_PRODUCT);
        payBill.setBusinessKey(productOrder.getId());
        payBill.setCreateTime(new Date());
        payBill.setUser_id(productOrder.getUser_id());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(productOrder.getShop_id());
        return payBill;
    }

    private ProductOrderDetail product2productOrderDetail(Product product) {
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product,productOrderDetail);
        return productOrderDetail;
    }

    private OrderAddress userAddress2orderAddress(UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setContacts(userAddress.getContacts());
        return orderAddress;
    }

    @Autowired
    private ShopMapper shopMapper;
    private ProductOrder getProductOrder(Map<String, Object> params,UserAddress userAddress,Product product, User user) {
//        Long productNum = Long.parseLong(params.get("product_num").toString());
        ProductOrder productOrder = new ProductOrder();

        productOrder.setDigest("[服务订单]购买"+product.getName()+"服务！");
        productOrder.setState(0);
        BigDecimal price  = product.getSaleprice();
        productOrder.setPrice(price);
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        Date lastPayTime = new Date(System.currentTimeMillis()+PayConstants.ORDER_TIMEOUT); //当前时间+30分钟
        productOrder.setLastPayTime(lastPayTime);
        productOrder.setProduct_id(product.getId());
        productOrder.setUser_id(user.getId());

//        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(userAddress.getFullAddress()), shopMapper.loadAll());
//        Shop shop = shopMapper.loadById(1L);
        productOrder.setShop_id(1L);

        productOrder.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        return productOrder;
    }

}

